package com.platform.user.service;

import com.baomidou.mybatisplus.plugins.Page;
import com.platform.bean.JsonResult;
import com.platform.bean.PageInfo;
import com.platform.exception.BaseException;
import com.platform.user.dao.AnnouncementDao;
import com.platform.user.entity.Announcement;
import com.platform.utils.Base64Utils;
import com.platform.utils.PrintMessageUtils;
import com.platform.utils.UploadFileToRemoteUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class AnnouncementService {

    @Resource
    private AnnouncementDao announcementDao;

    public Announcement queryById(int id) {
        return announcementDao.queryById(id);
    }

    public void deleteAnnouncementById(Integer id) {
        Announcement announcement = announcementDao.queryById(id);
        if (announcement == null) {
            throw new BaseException("查询到的公告对象为空");
        }
        deleteAllAnnouncementImage(announcement);
        announcementDao.deleteById(id);
    }

    public void addNewAnnouncement(Announcement announcement) throws IOException {
        String imageCover = processImageCover(announcement.getImageCover());
        String text = processRichText(announcement.getText());
        announcement.setImageCover(imageCover);
        announcement.setText(text);
        announcement.setIfHide(0);
        announcement.setIfTop(0);
        try {
            announcementDao.insert(announcement);
        } catch (Exception e) {
            deleteAllAnnouncementImage(announcement);
        }
    }

    public int topAnnouncement(Announcement announcement) throws IOException {
        announcement.setIfTop(1);
        Announcement countAnnouncement = new Announcement();
        countAnnouncement.setIfTop(1);
        long count = announcementDao.count(countAnnouncement);
        if (count > 4) {
            return 1;
        }
        announcementDao.update(announcement);
        return 0;
    }

    public void cancelTopAnnouncement(Announcement announcement) throws IOException {
        announcement.setIfTop(0);
        announcementDao.update(announcement);
    }

    public void updateAnnouncement(Announcement announcement) throws IOException {
        if (!announcement.getImageCover().isEmpty()) {
            String imageCover = processImageCover(announcement.getImageCover());
            announcement.setImageCover(imageCover);
        }
        String text = processRichText(announcement.getText());
        announcement.setText(text);
        announcement.setIfHide(0);
        announcement.setIfTop(announcement.getIfTop());
        announcement.setUpdateTime(new Date());
        System.out.println(announcement.toString());
        announcementDao.update(announcement);
    }

    public PageInfo<Announcement> queryAnnouncementByPage(Map<String, Object> params) {
        Integer pageIndex = (Integer) params.get("pageIndex");
        Integer pageSize = (Integer) params.get("pageSize");
        Page<Map> page = new Page<>(pageIndex, pageSize);
        List<Announcement> announcementList = announcementDao.queryByPage(page, params);
        return new PageInfo<>(pageIndex, pageSize, announcementDao.countByParams(params), announcementList);
    }

    /**
     * 删除公告的所有图片（包括封面、富文本图片）
     *
     * @param announcement 公告
     */
    private void deleteAllAnnouncementImage(Announcement announcement) {
        // 删除封面图片
        UploadFileToRemoteUtils.deleteFileFromRemoteServer(announcement.getImageCover(), "/opt/docker/apache/www/images/lost_and_found");
        List<String> fileList = extractFileNamesFromRichText(announcement.getText());
        // 删除富文本图片
        for(String x: fileList) {
            UploadFileToRemoteUtils.deleteFileFromRemoteServer(x, "/opt/docker/apache/www/images/lost_and_found");
        }
    }

    /**
     * 将base64封面图片转换为url
     *
     * @param imageCover base64图片
     * @return 图片url
     * @throws IOException 异常
     */
    private String processImageCover(String imageCover) throws IOException {
        StringBuilder fileName = new StringBuilder();
        Map<String, String> imageTypeAndCode = Base64Utils.splitImageTypeAndCode(imageCover);
        String imageType = null;
        String base64Data = null;

        if (imageTypeAndCode != null) {
            imageType = imageTypeAndCode.get("imageType");
            base64Data = imageTypeAndCode.get("base64Data");
        }

        fileName.append(System.currentTimeMillis()).append(".").append(imageType);
        // Base64转文件
        MultipartFile multipartFile = Base64Utils.convertBase64ToMultipart(base64Data, fileName.toString());
        JsonResult jsonResult = UploadFileToRemoteUtils.uploadFileToRemoteServer(multipartFile, "/opt/docker/apache/www/images/lost_and_found");
        return (String) jsonResult.getData();
    }

    /**
     * 处理富文本，并且将文本内的所有base64图片转换成url
     *
     * @param richText 富文本
     * @return 转换之后的富文本
     * @throws IOException 异常
     */
    private String processRichText(String richText) throws IOException {
        // 正则表达式匹配 Base64 图片
        Pattern base64ImagePattern = Pattern.compile("<img\\s+[^>]*src=[\"']data:image\\/([^;]+);base64,([^\"']+)[\"'][^>]*>", Pattern.CASE_INSENSITIVE);
        Matcher matcher = base64ImagePattern.matcher(richText);

        StringBuffer result = new StringBuffer();

        while (matcher.find()) {
            String fileType = matcher.group(1);
            String base64Data = matcher.group(2);

            // 设置随机文件名
            String fileName = System.currentTimeMillis() + "." + fileType;

            // Base64转文件（假设这个方法存在并正确实现）
            MultipartFile multipartFile = Base64Utils.convertBase64ToMultipart(base64Data, fileName);
            JsonResult jsonResult = UploadFileToRemoteUtils.uploadFileToRemoteServer(multipartFile, "/opt/docker/apache/www/images/lost_and_found");

            // 假设 jsonResult.getData() 返回的是图片的 URL
            String imageUrl = (String) jsonResult.getData();

            // 替换匹配的内容
            matcher.appendReplacement(result, "<img src=\"" + imageUrl + "\">");
        }
        matcher.appendTail(result);

        return result.toString();
    }

    /**
     * 从富文本中提取 <img src="..."> 的 URL，然后获取文件名
     *
     * @param richText 富文本
     * @return 文件名列表
     */
    private List<String> extractFileNamesFromRichText(String richText) {
        List<String> fileNames = new ArrayList<>();
        Pattern imgPattern = Pattern.compile("<img\\s+[^>]*src=[\"']([^\"']+)[\"'][^>]*>", Pattern.CASE_INSENSITIVE);
        Matcher matcher = imgPattern.matcher(richText);

        while (matcher.find()) {
            String imageUrl = matcher.group(1);
            String fileName = getFileNameFromUrl(imageUrl);
            if (fileName != null) {
                fileNames.add(fileName);
            }
        }

        return fileNames;
    }

    /**
     * 从图片url中提取文件名
     *
     * @param url 图片url
     * @return 文件名
     */
    private static String getFileNameFromUrl(String url) {
        // 假设 URL 是以 http:// 或 https:// 开头，并且文件名在最后一个 '/' 之后
        int lastSlashIndex = url.lastIndexOf('/');
        if (lastSlashIndex != -1) {
            return url.substring(lastSlashIndex + 1);
        }
        return null;
    }
}
